<template>
  <div class="app-container">
    <el-form ref="placeCodeForm" v-loading="formLoading" :rules="rules" :model="form" label-position="top">
      <el-row type="flex" :gutter="20">

        <el-col :span="24">
          <el-form-item label="培训机构" prop="title" style="width: 400px">
            <el-input v-model="form.company" placeholder="请输入培训机构" clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="培训种类（、顿号隔开）" prop="title" style="width: 400px">
            <el-input v-model="form.label" placeholder="请输入培训种类" clearable  />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="培训地址" prop="title" style="width: 400px">
            <el-input v-model="form.transaddress" placeholder="请输入培训地址" clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系电话" prop="title" style="width: 400px">
            <el-input v-model="form.mobile" placeholder="请输入联系电话" clearable  />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="培训行业" prop="postId" style="width: 400px">
            <el-cascader v-model="form.postId" :options="category" :props="optionProps" filterable :show-all-levels="false"></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="培训描述" prop="Abstract">
            <div class="container">
              <Toolbar :editor="editor" :default-config="toolbarConfig" :mode="mode" />
              <Editor v-model="form.describer" :default-config="editorConfig" :mode="mode" @onCreated="onCreated" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {getTrainByIdApi, editTrainApi, findJobNameApi} from '@/api/trainCode'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
  components: { Editor, Toolbar },
  name: 'PlaceCodeDetail',
  data(){
    return{
      editor: null,
      category: [],
      //期望职位级联选择器配置
      optionProps: {
        value: 'id',
        label: 'jobTitle',
        children: 'subLevelModelList',
      },
      toolbarConfig: {
        excludeKeys: [
          // 排除菜单组，写菜单组 key 的值即可
          'group-video' // 去掉视频
        ]
      },
      editorConfig: { MENU_CONF: {}, placeholder: '' },
      mode: 'default',
      uploadUrl: process.env.VUE_APP_UPLOAD_API,
      dialogImageUrl: '',
      dialogVisible: false,
      form: {
        id: null,
        trainName: '',
        company:'',
        trainTime:'',
        transaddress: '',
        describer:'',
        postId: null
      },
      rules: {
        label: [{ required: true, trigger: 'blur', message: '请输入培训种类' }],
        company: [{ required: true, trigger: 'blur', message: '请输入培训机构' }],
        trainTime: [{ required: true, trigger: 'blur', message: '请选择培训时间' }],
        transaddress: [{ required: true, trigger: 'blur', message: '请输入培训地址' }],
        describer: [{ required: true, trigger: 'blur', message: '请输入培训描述' }],
        postId: [{ required: true, trigger: 'blur', message: '请选择行业' }]
      },
      formLoading: false,
      placeTypeLoading:true,
      placeTypeOption:[],
    }
  },
  props:['id','closeDialog'],
  methods:{
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    handleAvatarSuccess(res, file) {
      this.form.imaUrl = res.imgURL;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    submit(){
      this.$refs.placeCodeForm.validate(valid => {
        if (valid) {
          const loading=this.$loading({
            text:'提交中'
          })
          if(this.form.id==null)
          {
            this.form.id = 0;
          }
          const form=JSON.parse(JSON.stringify(this.form));
          if(typeof form.postId==='object'){
            form.postId=form.postId[2];
          }
          editTrainApi(form).then((res)=>{
            this.$message.success('保存成功');
            this.closeDialog(0);
          }).catch(()=>{
            this.$message.error('保存失败');
          }).finally(()=>{
            loading.close();
          })
        } else {
          return false
        }
      })
    },
    //获取职位类别
    getJobCategory(){
      this.formLoading=true
      findJobNameApi().then((res)=>{
        this.category=res;
      }).finally(()=>{
        this.formLoading=false;
      })
    },
    getDetail(){
      this.formLoading=true;
      getTrainByIdApi({id:this.id}).then((res)=>{
        this.form=res;
      }).finally(()=>{
        this.formLoading=false;
      })
    },
  },
  mounted() {
    if(this.id){
      this.getDetail();
    }
    this.getJobCategory()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  created() {
    this.editorConfig.placeholder = '请输入使用说明内容...'
    this.editorConfig.MENU_CONF['uploadImage'] = {
      timeout: 5 * 1000, // 5s
      fieldName: 'image',
      // 用户自定义上传图片
      customUpload(file, insertFn) {
        var axios = require('axios')
        var FormData = require('form-data')
        var data = new FormData()
        data.append('file', file) // file 即选中的文件
        var config = {
          method: 'post',
          url: process.env.VUE_APP_UPLOAD_API, // 上传图片地址
          data: data
        }
        axios(config)
          .then(function(res) {
            const url = res.data.imgURL // 拼接成可浏览的图片地址
            insertFn(url, '使用说明', url) // 插入图片
          })
          .catch((res) => {
            console.log(res)
          })
      }
    }
  },
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
</style>
<style scoped>
/*
*让select撑开
*/
.el-select,.el-cascader{
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
